#pragma once
#include <iostream>
#include <queue>
using namespace std;

const int defaultcap = 5; // test

template <class T>
class BlockQueue
{
public:
    BlockQueue(int cap = defaultcap)
        : _capacity(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);

    }
    bool IsFull()
    {
        return _q.size()==_capacity;
    }
    bool IsEmpty()
    {
        return _q.size()==0;
    }
    bool Push(const T &in)//生产
    {
        pthread_mutex_lock(&_mutex);
        while(IsFull())//如果满了，就等待
        {
            //阻塞等待
            pthread_cond_wait(&_p_cond,&_mutex);
        }
        //没有满就继续Push
        _q.push(in);
        pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);

        return true;
    }
    bool Pop(T *out)//消费
    {
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        *out=_q.front();
        _q.pop();
        pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);
        
        return true;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    queue<T> _q;
    int _capacity; //_q.size()==_capacity,满了，不能生产
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond; // 给生产者
    pthread_cond_t _c_cond; // 给消费者

    int _productor_water_line;
    int _consumer_water_line;

};